package com.fjzx.androidframe.network.callback;

import android.net.ParseException;
import android.util.MalformedJsonException;

import com.fjzx.androidframe.network.entity.BaseResponse;
import com.fjzx.androidframe.network.ResponseMap;
import com.fjzx.androidframe.xlogger.XLogger;

import org.json.JSONException;

import java.net.ConnectException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;

/**
 * 基础网络请求回调类，封装异常处理
 *
 * @param <T>
 * @author xiongyongcong
 */
public abstract class BaseCallback<T> implements Callback<BaseResponse<T>> {
    @Override
    public void onResponse(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
        XLogger.d("BaseCallback onReponse " + response.code());
        if (response.isSuccessful() && response.code() == ResponseMap.OK) {
            BaseResponse<T> baseResponse = response.body();
            int code = baseResponse.getCode();
            // 状态码为200时，处理服务器返回数据
            XLogger.d("BaseCallback onReponse server code " + baseResponse.getCode());
            if (code == ResponseMap.SUCCESS || code == ResponseMap.OK) {
                response(baseResponse);
            } else {
                error(new Exception(ResponseMap.getReponseMessage(code)));
            }
        } else {
            error(new Exception(ResponseMap.getReponseMessage(response.code())));
        }
    }

    @Override
    public void onFailure(Call<BaseResponse<T>> call, Throwable e) {
        XLogger.e(e, "BaseCallback onFailure");
        if (e instanceof HttpException) {
            // 处理Http异常
            handleHttpException((HttpException) e);
        } else if (e instanceof ConnectException) {
            // 网络连接异常
            error(new Exception("网络连接异常，请检查您的网络"));
        } else if (e instanceof JSONException || e instanceof ParseException || e instanceof MalformedJsonException) {
            // Json解析，Http解析异常
            error(new Exception("数据解析错误"));
        } else {
            // 未知异常
            error(new Exception("未知异常"));
        }
    }

    /**
     * Http异常处理
     *
     * @param e
     */
    private void handleHttpException(HttpException e) {
        int code = e.code();
        error(new Exception(ResponseMap.getReponseMessage(code)));
    }

    /**
     * 正确数据回调
     *
     * @param data 数据
     */
    public abstract void response(BaseResponse<T> data);

    /**
     * 异常回调
     *
     * @param e 异常
     */
    public abstract void error(Exception e);
}
